package data.viewmodel_layer.reuse

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

open class BaseViewModelImpl : BaseViewModel, ViewModel() {
    override fun <T> performAction(
        resultLiveData: MutableLiveData<Resource<T>>,
        apiCall: () -> Call<T>
    ) {
        resultLiveData.value = Resource.Loading()

        val call = apiCall()
        call.enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                if (response.isSuccessful) {
                    val responseBody = response.body()
                    responseBody?.let {
                        resultLiveData.value = Resource.Success(it)
                    }
                } else {
                    resultLiveData.value = Resource.Error("请求失败")
                }
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                resultLiveData.value = Resource.Error("网络错误")
            }
        })
    }
}